package com.tuling.netty.command;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

public class CmdHandlerMapping {
    private static List<CmdHandler> handlers;

    static {
        handlers = new ArrayList<>();
        handlerRegister(handlers);
    }

    /**
     * 注册命令处理器
     *
     * @param handlers
     */
    private static void handlerRegister(List<CmdHandler> handlers) {
//        handlers.add(new HeartbeatCmdHandler());
//        handlers.add(new KilledCmdHandler());
        handlers.add(new LoginCmdHandler());
        handlers.add(new AuditCmdHandler());

        // 通过SPI方式, 支持自定义CmdHandler
        ServiceLoader<CmdHandler> customHandlers = ServiceLoader.load(CmdHandler.class);
        Iterator<CmdHandler> iterator = customHandlers.iterator();
        while (iterator.hasNext()) {
            handlers.add(iterator.next());
        }
    }

    /**
     * 针对命令进行命令处理器的匹配, 参考Spring MVC的匹配方式。
     *
     * @param cmd
     * @return
     */
    public CmdHandler getHandler(Cmd cmd) {
        for (CmdHandler handler : handlers) {
            if (handler.supports(cmd)) {
                return handler;
            }
        }

        return new DefaultCmdHandler();
    }
}